//
//  ChooseAddressVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/5/10.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ChooseAddressVC.h"
#import "AddressCell.h"
#import "AddressVC.h"
#import "Common.h"
#import "AddressVC.h"
#import <Masonry.h>
#import "PlaceOrderModel.h"
#import "EditAddressCell.h"
#import <MJRefresh.h>
#import "WKProgressHUD.h"
#import "CDAddressVC.h"
@interface ChooseAddressVC ()
{
    UIImageView * nav;
    Common * Com;
    UITableView * table;
    NSMutableArray * dataSouce;
    PlaceOrderModel * placeModel;
    WKProgressHUD *hud;

    UIScrollView * scroll;
    NSString * removeAddress;
    int page;
    int totalPage;
}
@end

@implementation ChooseAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayColor;
    dataSouce = [[NSMutableArray alloc]init];
    placeModel = [[PlaceOrderModel alloc]init];
    removeAddress = [[NSString alloc]init];
    
    page = 1;
    totalPage = 1;
    
    Com = [[Common alloc]init];
    if ([_addresstype isEqualToString:@"0"]) {
        nav = [self createNav:@"起运地选择"];
    }else{
        nav = [self createNav:@"目的地选择"];
    }
    [self.view addSubview:nav];
    [self createUI];
    
    UIButton * btnBig =[UIButton buttonWithType:UIButtonTypeCustom];
    [btnBig addTarget:self action:@selector(goBackLast) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:btnBig];
    [btnBig mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(nav.mas_left).with.offset(14);
        make.bottom.mas_equalTo(nav.mas_bottom).with.offset(-10*kHeight);
        make.size.mas_equalTo(CGSizeMake(60, 44));
    }];
}
-(void)goBackLast{
    
    
    
    if (self.callRemoveBack) {
        self.callRemoveBack(removeAddress);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)viewWillAppear:(BOOL)animated{
    
   
}


-(void)createUIAlertController:(NSString*)title
{
    
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"设置默认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction * action2 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:action1];
    [alert addAction:action];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
    
}

-(void)createUI{
    
    
//    scroll = [[UIScrollView alloc]init];
//    scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 65, Main_Width,Main_height-64*kHeight)];
//    scroll.backgroundColor = GrayColor;
//    scroll.contentOffset = CGPointMake(0, 0);
//    scroll.contentSize = CGSizeMake(Main_Width, Main_height);
//    scroll.bounces = NO;
//    scroll.userInteractionEnabled = YES;
//    scroll.delegate = self;
//    [self.view addSubview:scroll];
//
//    
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, 400*kHeight) style:UITableViewStylePlain];
    [table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    table.backgroundColor = GrayColor;
    [table setTableFooterView:[UIView new]];

    table.delegate = self;
    table.dataSource = self;
    [self.view addSubview:table];
    [table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(Main_Width, Main_height-64-70*kHeight));
        make.top.mas_equalTo(nav.mas_bottom).with.offset(0);
    }];

    UIView * btnView = [[UIView alloc]init];
    btnView.backgroundColor = GrayColor;
    [self.view addSubview:btnView];
    [btnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 70*kHeight));
        make.bottom.mas_equalTo(self.view.mas_bottom);
    }];
    
    
    UIButton * AddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    if ([_addresstype isEqualToString:@"0"]) {
        [AddBtn setTitle:@"新建发车地址" forState:UIControlStateNormal];
    }else{
        [AddBtn setTitle:@"新建收车地址" forState:UIControlStateNormal];
    }
    [AddBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [AddBtn addTarget:self action:@selector(pressAddBtn) forControlEvents:UIControlEventTouchUpInside];
    AddBtn.layer.borderWidth = 0.5;
    AddBtn.layer.cornerRadius = 5;
    AddBtn.layer.borderColor = YellowColor.CGColor;
    AddBtn.backgroundColor = YellowColor;
    [btnView addSubview:AddBtn];
    [AddBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(btnView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(293*kWidth, 40*kHeight));
        make.top.mas_equalTo(btnView.mas_top).with.offset(15*kHeight);
    }];
    
    [self loadData];
}

-(void)downRefresh{
    
    [table.mj_header endRefreshing];
    [table.mj_footer endRefreshing];
    page = 1;
    [self loadData];
    NSLog(@"刷新");
}

-(void)loadData{
    
    hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    if ([_addresstype isEqualToString:@"1"]) {
        [dic setObject:@"1" forKey:@"addresstype"];//收车
    }else{
        [dic setObject:@"0" forKey:@"addresstype"];//发车
    }
    NSLog(@"%@",addressUser_Url);
    NSString * string = nil;
    if (self.CityListName.length == 0) {
        
        string = [NSString stringWithFormat:@"%@?addresstype=%@&isVeneer=0",addressUser_Url,dic[@"addresstype"]];
 
    }else{
        string = [NSString stringWithFormat:@"%@?addresstype=%@&isVeneer=1",addressUser_Url,dic[@"addresstype"]];
    }

    NSLog(@"%@",string);
    
    [Common requestWithUrlString:string contentType:@"application/json" finished:^(id responseObj) {

        dataSouce = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud dismiss:YES];
//            
//            if (dataSouce.count==0) {
//                
//                [table mas_updateConstraints:^(MASConstraintMaker *make) {
//                    make.height.mas_equalTo(130*kHeight);
//                }];
//            }else{
//                [table mas_updateConstraints:^(MASConstraintMaker *make) {
//                    make.height.mas_equalTo(dataSouce.count*130*kHeight);
//                }];
//            }
            scroll.scrollEnabled = NO;
            if (dataSouce.count>=4) {
            scroll.contentSize = CGSizeMake(Main_Width, dataSouce.count*130*kHeight+100);
            scroll.scrollEnabled = YES;
            }
            [table reloadData];
        });
        
    } failed:^(NSString *errorMsg) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud dismiss:YES];
        });
    }];

}


-(void)pressAddBtn{
    
    
    if (self.CityListName.length==0) {
        
        AddressVC * address = [[AddressVC alloc]init];
        address.addresstype = self.addresstype;
        address.navtitle = @"2";
        [self.navigationController pushViewController:address animated:YES];

  
    }else{
        CDAddressVC * address = [[CDAddressVC alloc]init];
        address.addresstype = self.addresstype;
        address.navtitle = @"2";
        address.CityListName = self.CityListName;
        address.CityListCode = self.CityListCode;
        [self.navigationController pushViewController:address animated:YES];

    }
    
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str=@"str";
    EditAddressCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
        if (cell ==nil) {
            cell = [[EditAddressCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
    
    NSMutableDictionary * dic = dataSouce[indexPath.row];
    placeModel = [PlaceOrderModel ModelWithDic:dic];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString * cityName = nil;
    if (self.CityListName.length==0) {
        if ([placeModel.provinceName isEqualToString:placeModel.cityName]) {
            
            cityName = [NSString stringWithFormat:@"%@%@",placeModel.provinceName,placeModel.countyName];
        }else{
            cityName = [NSString stringWithFormat:@"%@%@%@",placeModel.provinceName,placeModel.cityName,placeModel.countyName];
        }
    }else{
        cityName = [NSString stringWithFormat:@"%@-%@",dic[@"cityName"],dic[@"countyName"]];
    }

    cell.CityName.text = cityName;
//    cell.StoreName.text = placeModel.unitName;
    cell.StoreName.text = @"";

    cell.AddressName.text = placeModel.address;
    NSString * people = [NSString stringWithFormat:@"%@",placeModel.contact];
    NSString * iphone = [NSString stringWithFormat:@"%@",placeModel.phone];
    cell.PeopleName.text = people;
    cell.iphone.text = iphone;
    cell.MRbtn.indexpath = indexPath;
    cell.BJbtn.indexpath = indexPath;
    cell.SCbtn.indexpath = indexPath;
    if ([dataSouce[indexPath.row][@"isDefault"] isEqualToString:[NSString stringWithFormat:@"F"]]) {
        cell.leftImage.image = [UIImage imageNamed:@"btn_unselect"];
    }else{
        cell.leftImage.image = [UIImage imageNamed:@"btn_select"];
    }
    [cell.MRbtn addTarget:self action:@selector(pressMrBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.BJbtn addTarget:self action:@selector(pressBjBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.SCbtn addTarget:self action:@selector(pressScBtn:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
}


-(void)pressScBtn:(NewBtn*)sender{
    
    NSInteger index = sender.indexpath.row;
    NSString * string = dataSouce[index][@"id"];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:string forKey:@"id"];
    
    
    
    NSString * stringUrl = nil;
    if (self.CityListName.length == 0) {
        
        stringUrl = [NSString stringWithFormat:@"%@?isVeneer=0",addressDelete_Url];
        
    }else{
        stringUrl = [NSString stringWithFormat:@"%@?isVeneer=1",addressDelete_Url];
        
    }

    
    
    [Com afPostRequestWithUrlString:stringUrl parms:dic finishedBlock:^(id responseObj) {
        NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
        int success = [dicObj[@"success"] intValue];
        if (success == 1) {
            removeAddress = [NSString stringWithFormat:@"%@",dataSouce[index][@"id"]];
        }

        [dataSouce removeObjectAtIndex:index];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.indexpath.row inSection:0];
        NSMutableArray* rowToInsert = [NSMutableArray arrayWithObject:indexPath];
        [table beginUpdates];
        
        [table deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationLeft];
        [table endUpdates];
        [self loadData];

    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(void)pressBjBtn:(NewBtn*)sender{
    NSLog(@"pressBjBtn:%ld",(long)sender.indexpath.row);
    if (self.CityListName.length>0) {
        
        CDAddressVC * address = [[CDAddressVC alloc]init];
        address.addresstype = dataSouce[sender.indexpath.row][@"addressType"];
        address.dataSouce = dataSouce[sender.indexpath.row];
        address.navtitle = dataSouce[sender.indexpath.row][@"addressType"];
        address.CityListName = self.CityListName;
        address.CityListCode = self.CityListCode;
        
        [self.navigationController pushViewController:address animated:YES];
  
    }else{
        
        AddressVC * address = [[AddressVC alloc]init];
        address.addresstype = dataSouce[sender.indexpath.row][@"addressType"];
        address.dataSouce = dataSouce[sender.indexpath.row];
        address.navtitle = dataSouce[sender.indexpath.row][@"addressType"];
        [self.navigationController pushViewController:address animated:YES];
    }
}

-(void)pressMrBtn:(NewBtn*)sender{
    NSLog(@"pressMrBtn:%ld",(long)sender.indexpath.row);
    NSInteger index = sender.indexpath.row;
    NSString * string = dataSouce[index][@"id"];

    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:string forKey:@"id"];
    
    
    if (self.CityListName.length>0) {
        
        [dic setObject:@"1" forKey:@"isVeneer"];
        
    }
    
    [Com afPostRequestWithUrlString:address_Yes_Fault_Url parms:dic finishedBlock:^(id responseObj) {
        
        NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
     
        NSLog(@"%@",dicObj);
        [self loadData];
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130*kHeight;
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return dataSouce.count;
}

/*
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{
//    [tableView setEditing:YES animated:YES];
    return UITableViewCellEditingStyleDelete;
}
*/
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //延迟执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (self.callBack) {
            self.callBack(dataSouce[indexPath.row],_addresstype);
        }
        [self.navigationController popViewControllerAnimated:YES];
    });
}
/*
//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@"删除");
    
    NSString * string = dataSouce[indexPath.row][@"id"];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:string forKey:@"id"];
    [Com afPostRequestWithUrlString:addressDelete_Url parms:dic finishedBlock:^(id responseObj) {
        
        NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
        if ([dicObj[@"message"] isEqualToString:@"1"]) {
            NSInteger teger = indexPath.row;
            [dataSouce removeObjectAtIndex:teger];
            [table reloadData];
        }
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
    
}
 */
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}



@end
